from micropython import const
from machine import I2C
import ustruct

ADS1115_COMP_QUE_Pos		= const(0)
ADS1115_COMP_QUE_Msk		= const(0x3 << ADS1115_COMP_QUE_Pos)
ADS1115_COMP_QUE			= const(ADS1115_COMP_QUE_Msk)
ADS1115_COMP_QUE_0			= const(0x1 << ADS1115_COMP_QUE_Pos)
ADS1115_COMP_QUE_1			= const(0x2 << ADS1115_COMP_QUE_Pos)

ADS1115_DR_Pos				= const(5)
ADS1115_DR_Msk				= const(0x7 << ADS1115_DR_Pos)
ADS1115_DR					= const(ADS1115_DR_Msk)
ADS1115_DR_0				= const(0x1 << ADS1115_DR_Pos)
ADS1115_DR_1				= const(0x2 << ADS1115_DR_Pos)
ADS1115_DR_2				= const(0x4 << ADS1115_DR_Pos)

ADS1115_COMP_MODE_Pos		= const(4)
ADS1115_COMP_MODE_Msk		= const(0x1 << ADS1115_COMP_MODE_Pos)
ADS1115_COMP_MODE			= const(ADS1115_COMP_MODE_Msk)

ADS1115_MODE_Pos			= const(8)
ADS1115_MODE_Msk			= const(0x1 << ADS1115_MODE_Pos)
ADS1115_MODE				= const(ADS1115_MODE_Msk)

ADS1115_PGA_Pos				= const(9)
ADS1115_PGA_Msk				= const(0x7 << ADS1115_PGA_Pos)
ADS1115_PGA					= const(ADS1115_PGA_Msk)
ADS1115_PGA_0				= const(0x1 << ADS1115_PGA_Pos)
ADS1115_PGA_1				= const(0x2 << ADS1115_PGA_Pos)
ADS1115_PGA_2				= const(0x4 << ADS1115_PGA_Pos)

ADS1115_MUX_Pos				= const(12)
ADS1115_MUX_Msk				= const(0x7 << ADS1115_MUX_Pos)
ADS1115_MUX					= const(ADS1115_MUX_Msk)
ADS1115_MUX_0				= const(0x1 << ADS1115_MUX_Pos)
ADS1115_MUX_1				= const(0x2 << ADS1115_MUX_Pos)
ADS1115_MUX_2				= const(0x4 << ADS1115_MUX_Pos)

ADS1115_OS_Pos				= const(15)
ADS1115_OS_Msk				= const(0x1 << ADS1115_OS_Pos)
ADS1115_OS					= const(ADS1115_OS_Msk)

ADS1115_REG_CONVERSION		= const(0x00)
ADS1115_REG_CONFIG			= const(0x01)

class ADS1115:
	def __init__(self, i2c, addr=0x48):
		if i2c is None or i2c.__class__ != I2C:
			raise ValueError("I2C object needed as argument!")
		self._i2c = i2c
		self._addr = addr

	def measure(self):
		register_data = ADS1115_COMP_QUE						# 11  : Disable comparator and set ALERT/RDY pin to high-impedance (default)
		# register_data |= ADS1115_DR_2							# 100 : 128 SPS (default)
		register_data |= ADS1115_MODE							# 1   : Single-shot mode or power-down state (default)
		register_data &= ~ADS1115_PGA							# 000 : FSR = ±6.144 V (187.5μV)
		register_data |= ADS1115_PGA_1							# 010 : FSR = 2.048 (62.5uV)

		register_data |= ADS1115_MUX_2							# 100 : AINP = AIN0 and AINN = GND

		register_data |= ADS1115_OS								# 1   : Start a single conversion (when in power-down state)

		data = bytes([(register_data >> 8) & 0xFF, (register_data & 0xFF)])
		self._i2c.writeto_mem(self._addr, ADS1115_REG_CONFIG, data)

	def getData(self):
		_data = self._i2c.readfrom_mem(self._addr, ADS1115_REG_CONVERSION, 2)
		_mv = ustruct.unpack('>h', _data)[0]
		_mv = _mv * 62.5 / 1000.0
		if (_mv < 0):
			_mv = 0

		return _mv
